package com.ssyc.gsk_teacher.activity;

import android.content.Intent;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.base.Constants;
import com.ssyc.common.bean.ResultInfo;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.BqaManager;
import com.ssyc.common.manager.PickerManager;
import com.ssyc.common.manager.SrfManager;
import com.ssyc.common.utils.DateUtils;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.SnackbarUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.dialog.CustomDialogManager;
import com.ssyc.gsk_teacher.R;
import com.ssyc.gsk_teacher.adapter.AttenRvAdapter;
import com.ssyc.gsk_teacher.bean.AttenInfo;
import com.ssyc.gsk_teacher.bean.ClassInfo;
import com.ssyc.gsk_teacher.utils.ClassPoputil;
import com.ssyc.gsk_teacher.utils.ClassUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 考勤管理
 * Created by Administrator on 2018/7/1 0001.
 */

public class TeacherAttendanceManagementActivity extends BaseActivity implements View.OnClickListener {

    private ImageView ivBack;
    private RecyclerView rv;
    private SmartRefreshLayout srf;
    private RelativeLayout rlLoadingView;
    private LinearLayout rlContent;
    private ImageView ivEdit;
    private ImageView ivDetails;

    //标题栏的布局
    private LinearLayout llTitle;

    //保存
    private Button btSave;


    //是否获取班级列表数据完成的标识,没完成之前点击选择班级的弹框提示正在加载,不允许点击
    private boolean isLoadClassCompleted;

    //空视图
    private View emptyView;

    //头布局
    private View headView;

    //所有班级的列表
    private List<ClassInfo.ListBean> classInfos;

    //记录弹出展示班级列表PopUpWindow的选中位置的值,默认第一个被选中
    private int popSelectedPos = 0;

    //列表适配器
    private AttenRvAdapter adapter;

    //数据集合
    private List<AttenInfo.ListBean> oldDatas;
    private ImageView ivChooseDate;
    private TextView tvDate;

    private TextView tvDetails;

    //今天的日期,格式化yyyy-M-dd
    private String today;

    //记录选择的时间
    private String chooseDate;

    //记录克隆数据,用于比较用户是否做了修改
    private List<AttenInfo.ListBean> cloneDatas;

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.teacher_activity_attendance_management;
    }

    @Override
    protected void init() {

        showContent();

        //初始化视图
        initView();

        //初始化下拉刷新控件
        initSrf();

        //设置数据
        initRv();

        //请求班级数据
        httpClass();

    }


    /**
     * 初始化下拉刷新
     */
    private void initSrf() {
        SrfManager.setSmartByPullListener(srf, null);
    }

    /**
     * 初始化视图
     */
    public void initView() {
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        rv = findViewById(R.id.rv);
        srf = findViewById(R.id.srf);
        rlLoadingView = findViewById(R.id.rl_loading);
        rlLoadingView.setVisibility(View.VISIBLE);
        ivEdit = findViewById(R.id.iv_choose_class);
        ivEdit.setOnClickListener(this);
        rlContent = findViewById(R.id.rl_content);
        rlContent.setVisibility(View.GONE);
        //标题栏
        llTitle = findViewById(R.id.ll_title);

        btSave = findViewById(R.id.bt_save);
        btSave.setOnClickListener(this);

        ivDetails = findViewById(R.id.iv_details);
        ivDetails.setOnClickListener(this);

        btSave.setVisibility(View.INVISIBLE);
        ivDetails.setVisibility(View.INVISIBLE);

        //今天的日期时间
        today = DateUtils.getTime(new Date(), "yyyy-M-dd");

        chooseDate = DateUtils.getTime(new Date(), "yyyy-M-dd");
    }

    /**
     * 请求班级里列表数据
     */
    private void httpClass() {
        ClassUtil.httpClass(rlLoadingView, this, new ClassUtil.onSuccessListener() {
            @Override
            public void onSuccess(List<ClassInfo.ListBean> datas) {
                //回调班级数据
                classInfos = datas;

                //改变加载完成的标记
                isLoadClassCompleted = true;

                //请求页面列表数据
                httpPageData(popSelectedPos, BqaManager.NORML);
            }

            @Override
            public void hasNoData() {
                ivEdit.setVisibility(View.INVISIBLE);
                ivDetails.setVisibility(View.INVISIBLE);
            }
        });
    }

    /**
     * 弹出展示班级列表的方法
     */
    private void showClassPop() {
        ClassPoputil.showClassPop(this, classInfos, popSelectedPos, llTitle, new ClassPoputil.onPopItemClickListener() {
            @Override
            public void onItemClick(int pos) {

                //记录当前点击条目的位置
                popSelectedPos = pos;

                //请求页面数据
                httpPageData(popSelectedPos, BqaManager.NORML);
            }
        });
    }


    /**
     * 设置列表
     */
    private void initRv() {
        cloneDatas = new ArrayList<>();
        oldDatas = new ArrayList<>();
        headView = View.inflate(this, R.layout.teacher_headview_attendance, null);
        ivChooseDate = headView.findViewById(R.id.iv_choose_date);
        tvDate = headView.findViewById(R.id.tv_date);
        tvDetails = headView.findViewById(R.id.tv_details);
        ivChooseDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //选择日期
                chooseTimePicker();
            }
        });
        emptyView = View.inflate(this, R.layout.base_rv_common_empty_view, null);
        TextView tvMsg = emptyView.findViewById(R.id.tv_content);
        tvMsg.setText("该班级暂无学生");
        adapter = new AttenRvAdapter(this, R.layout.teacher_rv_attendance_manager, oldDatas);
        adapter.addHeaderView(headView);
    }

    /**
     * 弹出选择日期的弹框
     */
    private void chooseTimePicker() {
        PickerManager.showPickerByYeaerAndMonthAndDayByLimit(this, new PickerManager.onSelectedListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                //记录选择的开始时间
                chooseDate = DateUtils.getTime(date, "yyyy-M-dd");
                if (chooseDate.equals(today)) {
                    tvDate.setText("今日考勤汇总");
                } else {
//                    tvDate.setText(DateUtils.getTime(date, "yyyy年-M月-dd日"));
                    tvDate.setText(DateUtils.getTime(date, "yyyy-M-dd") + "\n考勤汇总");
                }

                //刷新适配器起数据
                httpPageData(popSelectedPos, BqaManager.PULLREFRESH);
            }
        });
    }


    /**
     * 请求页面数据的方法
     *
     * @param popSelectedPos
     */
    private void httpPageData(int popSelectedPos, int method) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "5");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("role", AccountUtils.getRole(this));
        map.put("classnum", classInfos.get(popSelectedPos).getClassnum());
        map.put("attendance_date", chooseDate);
        map.put("apptoken", AccountUtils.getToken(this));
        map.put("platform", "8");

        HttpUtils.post(HttpAdress.ATTENDANCEMANAGEMENT, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                BqaManager.setErrorNet(rlLoadingView, srf, method, adapter);
            }

            @Override
            public void onResponse(String response, int id) {
                if (rlLoadingView != null && rlLoadingView.getVisibility() == View.VISIBLE) {
                    rlLoadingView.setVisibility(View.GONE);
                }
                if (rlContent != null && rlContent.getVisibility() != View.VISIBLE) {
                    rlContent.setVisibility(View.VISIBLE);
                }

                if (!TextUtils.isEmpty(response)) {
                    AttenInfo info = null;

                    try {
                        info = GsonUtil.jsonToBean(response, AttenInfo.class);
                    } catch (Exception e) {
                        Log.i("test", "数据解析异常");
                    }

                    if (null != info && "200".equals(info.getState())) {

                        //设置头部数据
                        setHeadViewData(info);

                        //返回成功,设置列表数据
                        List<AttenInfo.ListBean> newDatas = info.getList();

                        if (newDatas != null) {
                            //记录克隆数据,注意:不能直接AddAll方法
                            cloneDatas.clear();
                            for (int i = 0; i < newDatas.size(); i++) {
                                AttenInfo.ListBean listBean = new AttenInfo.ListBean();
                                listBean.setATTENDANCE_TYPE(newDatas.get(i).getATTENDANCE_TYPE());
                                listBean.setIcon(newDatas.get(i).getIcon());
                                listBean.setName(newDatas.get(i).getName());
                                listBean.setSttel(newDatas.get(i).getSttel());
                                cloneDatas.add(listBean);
                            }

                            //没有数据的情况
                            if (newDatas.size() == 0) {
                                //证明没有学生数据
                                btSave.setVisibility(View.INVISIBLE);
                                ivDetails.setVisibility(View.INVISIBLE);
                            } else {
                                btSave.setVisibility(View.VISIBLE);
                                ivDetails.setVisibility(View.VISIBLE);
                            }

                            if (method == BqaManager.NORML) {
                                oldDatas.clear();
                                oldDatas.addAll(newDatas);
                                BqaManager.setRv(emptyView, TeacherAttendanceManagementActivity.this, adapter, rv);
                            } else {
                                //更新数据
                                BqaManager.updateRvBySmf(method, srf, rv, oldDatas, newDatas, adapter);
                                adapter.setEnableLoadMore(false);
                            }
                        }
                    } else {
                        UiUtils.Toast("返回器返回异常,错误码是:" + info.getState(), false);
                        Log.i("test", "返回器返回异常,错误码是:" + info.getState());
                    }
                } else {
                    Log.i("test", "服务器返回数据为空");
                }
            }
        });
    }


    /**
     * 设置头部数据
     *
     * @param info
     */
    private void setHeadViewData(AttenInfo info) {
        //应到
        String total = info.getTotal_num();
        //迟到
        String late = info.getLate_num();
        //旷到
        String absent = info.getAbsent_num();
        //请假
        String leave = info.getLeave_num();
        //已到
        String aatenNum = info.getAtten_num();

        if ("0".equals(info.getAbsent_num()) && "0".equals(info.getLate_num()) && "0".equals(info.getLeave_num()) && "0".equals(info.getAtten_num())) {
            tvDetails.setText("");
        } else {
            tvDetails.setVisibility(View.VISIBLE);
            tvDetails.setText("应到 " + total + " 人," + "实到 " + aatenNum + " 人,迟到 " +
                    late + " 人,请假 " + leave + " 人,旷到 " + absent + " 人");
        }
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            //返回
            finish();
        } else if (id == R.id.iv_choose_class) {
            //选择班级
            if (isLoadClassCompleted) {
                //弹出选择班级的PopUpWindow
                showClassPop();
            } else {
                //没加载完成
                SnackbarUtil.ShortSnackbar(llBaseMain, Constants.LOADING, 0).show();
            }
        } else if (id == R.id.iv_details) {
            if (isLoadClassCompleted) {
                //跳转到分析界面
                Intent intent = new Intent(this, TeacherStudAnalyzeActivity.class);
                intent.putExtra("classnum", classInfos.get(popSelectedPos).getClassnum());
                startActivity(intent);
            } else {
                //没加载完成
                SnackbarUtil.ShortSnackbar(llBaseMain, Constants.LOADING, 0).show();
            }
        } else if (id == R.id.bt_save) {
            //保存
            doSaveAction();
        }
    }


    /**
     * 保存修改的考勤记录
     */
    private void doSaveAction() {
        if (hasUpdate()) {
            if (hasCompleteUpdate()) {
                //是否所有的学生都选择了考勤记录
                //修改过,进行上传
                CustomDialogManager.show(this, "保存中...");
                Map<String, String> map = new HashMap<>();
                map.put("type", "4");
                map.put("acc", AccountUtils.getAccount(this));
                map.put("role", AccountUtils.getRole(this));
                map.put("apptoken", AccountUtils.getToken(this));
                map.put("classnum", classInfos.get(popSelectedPos).getClassnum());
                map.put("attendance_date", chooseDate);
                map.put("platform", "8");
                map.put("list", GsonUtil.listToJson(oldDatas));

                HttpUtils.post(HttpAdress.SAVAATTENDANCEMANAGEMENT, map, this, new HttpUtils.CallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        CustomDialogManager.dissmiss();
                        UiUtils.Toast(BaseApplication.ERROR + ",保存失败", false);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        if (!TextUtils.isEmpty(response)) {
                            ResultInfo info = null;
                            try {
                                info = GsonUtil.jsonToBean(response, ResultInfo.class);
                            } catch (Exception e) {
                                Log.i("test", "数据解析异常");
                            }
                            if (null != info && "200".equals(info.getState())) {
                                //保存成功
                                UiUtils.Toast("保存成功", false);
                                //关闭当前页面
                                finish();
                            } else {
                                UiUtils.Toast("保存失败,错误码是:" + info.getState(), false);
                                Log.i("test", "保存失败,错误码是:" + info.getState());
                            }
                        }
                    }
                });
            } else {
                SnackbarUtil.ShortSnackbar(llBaseMain, "考勤记录未填写完整,请检查", Snackbar.LENGTH_SHORT).show();
                return;
            }

        } else {
            //没有做过修改,不需要上传
            SnackbarUtil.ShortSnackbar(llBaseMain, "未做任何修改,不需要上传", Snackbar.LENGTH_SHORT).show();
            return;
        }
    }

    /**
     * 判读是否所有学生都填写了考勤记录方法
     *
     * @return
     */
    private boolean hasCompleteUpdate() {
        boolean res = true;
        for (int i = 0; i < oldDatas.size(); i++) {
            if (TextUtils.isEmpty(oldDatas.get(i).getATTENDANCE_TYPE())) {
                res = false;
                break;
            }
        }
        return res;
    }

    /**
     * 判断是否对考勤记录做过修改的方法
     */

    private boolean hasUpdate() {
        boolean res = false;
        for (int i = 0; i < oldDatas.size(); i++) {
            if (!oldDatas.get(i).getATTENDANCE_TYPE().equals(cloneDatas.get(i).getATTENDANCE_TYPE())) {
                res = true;
                break;
            }
        }
        return res;
    }


    /**
     * 释放适配器的handler对象
     */
    @Override
    protected void onDestroy() {
        if (adapter != null) {
            adapter.releaseHandler();
        }
        super.onDestroy();
    }
}
